# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4

##
## Copyright (C) 2009 - George Y. Kussumoto <georgeyk.dev@gmail.com>
##
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public License
## as published by the Free Software Foundation; either version 2
## of the License, or (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., or visit: http://www.gnu.org/.
##
##
""" Hero Page Definition """

import google.appengine.ext.db as db

from twitheroapp.base import BaseTemplatePage
from twitheroapp.models.battle import Battle
from twitheroapp.models.hero import Hero


class HeroPage(BaseTemplatePage):
    template_file = 'hero.html'
    page_values = {}

    def get(self, name):
        if not name:
            # Maybe a create/sign in page will better.
            return self.redirect('/')

        query = db.Query(Hero)
        query.filter('name =', name.lower())
        results = query.fetch(limit=1)
        if results:
            hero = results[0]
            self.page_values['hero'] = hero
            self.template_render()
        else:
            self.redirect('/createhero')

    def post(self, *args):
        hero = self.page_values['hero']
        opponent_name = self.request.get("opponent")
        if not opponent_name:
            # page error ?
            self.redirect('/hero/%s' % hero.name)
            return
        if opponent_name.lower() == hero.name:
            self.redirect('/hero/%s' % hero.name)
            return

        query = db.Query(Hero)
        query.filter('name =', opponent_name.lower())
        results = query.fetch(limit=1)
        if not results:
            self.redirect('/')
            return

        opponent = results[0]
        battle = Battle(fighter=hero.key(), opponent=opponent.key())
        battle.put()

        self.redirect('/battle/%s' % battle.key())
